<style lang="less">
    @import '../../../styles/common.less';

    .ivu-page-options-sizer {
        width: 100px;
    }
</style>

<template>
    <div>
        <Row v-if="currentPage">
            <Row class="margin-top-10">
                <Card>
                    <Row>
                        <Col span="4">
                            项目名称：
                            <Select v-model="searchData.project_id" style="width:50%">
                                <Option value="" >显示全部</Option>
                                <Option v-for="(item,index) in projectData" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </Col>
                        <Col span="4">
                            状态：
                            <Select v-model="searchData.status" style="width:50%">
                            <Option value="" >显示全部</Option>
                            <Option v-for="(item,index) in status_choices" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </Col>
                        <Col span="4">
                            紧急程度：
                            <Select v-model="searchData.urgency_level" style="width:50%">
                                <Option value="" >显示全部</Option>
                                <Option v-for="(item,index) in urgency_level_choices" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </Col>
                        <Col span="4">
                            开发人员：
                            <Select v-model="searchData.developer_id" style="width:50%">
                                <Option value="" >显示全部</Option>
                                <Option value="7" >张聪</Option>
                                <Option v-for="(item,index) in developerList" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </Col>
                        <Col span="4">
                            提需求人：
                            <Select v-model="searchData.demandUser" style="width:50%">
                                <Option v-for="(item,index) in demandUserData" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </Col>
                    </Row>
                </Card>
            </Row>
            <Row class="margin-top-10">
                <Col span="24">
                    <Card>
                        <p slot="title">需求管理</p>
                        <Row class="margin-bottom-10">
                            <Button type="primary" @click="modalAddDisplay">添加</Button>
                        </Row>

                        <Row class="edittable-table-height-con">
                            <!--<can-edit-table refs="table2" v-model="editInlineData" :columns-list="editInlineColumns"></can-edit-table>-->
                            <Table
                                    border :context="self"
                                    :columns="table_data.header"
                                    :data="table_data.data"
                                    @on-sort-change="tableSort"
                            ></Table>
                        </Row>
                        <Row class="margin-top-10">
                            <Page
                                    :current="table_data.current_page"
                                    :total="table_data.count"
                                    class="float-right"
                                    show-total
                                    show-sizer
                                    show-elevator
                                    @on-change="updateTableCurrentPage"
                                    @on-page-size-change="updateTablePageLength"
                                    :page-size-opts="[10, 25, 50, 100]"
                            ></Page>
                        </Row>

                    </Card>
                </Col>
            </Row>

        </Row>
        <add-page @closeAddPage="closeAddPage" v-else-if="addDataPage && actionData.length > 0"
                  :projectData="projectData"
                  :actionData="actionData"
        ></add-page>
        <update-page @closeUpdatePage="closeUpdatePage" v-else-if="updateDataPage && actionData.length > 0 && UpdateData"
                  :projectData="projectData"
                  :actionData="actionData"
                  :UpdateData="UpdateData"
        ></update-page>
        <detail-page @closeDetailPage="closeDetailPage" v-else-if="detailDataPage && actionData.length > 0 && detailData"
                     :projectData="projectData"
                     :actionData="actionData"
                     :detailData="detailData"
        ></detail-page>

    </div>
</template>

<script>
    import util from '../../../libs/util';
    import qs from 'qs';
    // import imgUpload from './imgUpload';
    import addPage from './add';
    import updatePage from './update';
    import detailPage from './detail';

    export default {
        components: {
            addPage,
            updatePage,
            detailPage
        },
        data () {
            return {
                // closeAddPage: false, // 当改值为true 时，说明添加页面中的返回按钮被点击了
                currentPage: true,
                addDataPage: false,
                updateDataPage: false,
                detailDataPage: false,
                modalAdd: false, // 是否显示模态对话框
                modalUpdate: false, // 是否显示模态对话框
                self: this,
                UpdateData: {},
                detailData: {},
                table_data: {
                    header: [
                        {
                            title: '编号',
                            type: 'index',
                            width: 60,
                            align: 'center'
                        },
                        // {
                        //     title: 'id',
                        //     key: 'id'
                        // },
                        {
                            title: '需求名称',
                            key: 'name',
                            sortable: 'custom',
                            align: 'center'
                        },
                        // {
                        //     title: '需求描述',
                        //     key: 'remark',
                        //     sortable: 'custom',
                        //     align: 'center'
                        // },
                        {
                            title: '项目-功能名称',
                            key: 'project__name_action__name',
                            sortable: 'custom',
                            align: 'center'
                        },
                        {
                            title: '状态',
                            key: 'status',
                            sortable: 'custom',
                            align: 'center',
                            render: (h, params) => {
                                let type = 'success';
                                if (params.row.status === 1) {
                                    type = 'warning';
                                } else if (params.row.status === 2) {
                                    type = 'primary';
                                } else if (params.row.status === 3) {
                                    type = 'info';
                                } else if (params.row.status === 4) {
                                    type = 'success';
                                } else if (params.row.status === 5) {
                                    type = '';
                                } else if (params.row.status === 11) {
                                    type = 'error';
                                } else if (params.row.status === 8) {
                                    type = 'error';
                                }

                                return h('Button', {
                                    props: {
                                        type: type,
                                        size: 'small'
                                    }
                                }, params.row.status_text);
                            }
                        },
                        {
                            title: '紧急度',
                            key: 'urgency_level',
                            sortable: 'custom',
                            align: 'center',
                            render: (h, params) => {
                                let type = 'success';
                                if (params.row.urgency_level === 1) {
                                    type = 'info';
                                } else if (params.row.urgency_level === 2) {
                                    type = 'primary';
                                } else if (params.row.urgency_level === 3) {
                                    type = 'warning';
                                } else if (params.row.urgency_level === 4) {
                                    type = 'error';
                                }

                                return h('Button', {
                                    props: {
                                        type: type,
                                        size: 'small'
                                    }
                                }, params.row.urgency_level_text);
                            }
                        },
                        {
                            title: '提需求人',
                            key: 'oper_user__username',
                            sortable: 'custom',
                            align: 'center'
                        },
                        {
                            title: '开发人',
                            key: 'developer',
                            align: 'center'
                        },
                        {
                            title: '创建时间',
                            key: 'create_date',
                            sortable: 'custom',
                            align: 'center'
                        },
                        // {
                        //     title: '预计完成时间',
                        //     key: 'complete_date',
                        //     sortable: 'custom',
                        //     align: 'center'
                        // },
                        {
                            title: '详情',
                            align: 'center',
                            render: (h, params) => {
                                return h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        icon: 'ios-search'
                                    },
                                    on: {
                                        click: () => {
                                            console.log('点击详情');
                                            console.log('params.row -->', params.row);
                                            this.detailData = params.row;
                                            this.modalDetailDisplay();
                                        }
                                    }
                                }, '查看详情');
                            }
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 200,
                            align: 'center',
                            render: (h, params) => {
                                if (params.row.status === 1) {
                                    return [
                                        h('Button', {
                                            props: {
                                                type: 'warning',
                                                size: 'small',
                                                icon: 'edit'
                                            },
                                            on: {
                                                'click': () => {
                                                    // 弹出修改界面框
                                                    console.log('params.row -->', params.row);
                                                    this.UpdateData = params.row;
                                                    this.modalUpdateDisplay();
                                                    // this.$refs['UpdateformValidate'].resetFields();
                                                    // this.modalUpdate = true;
                                                    // this.modalData.Update.formValidate.name = params.row.name;
                                                    // this.modalData.Update.formValidate.project_id = params.row.project_id;
                                                    // this.modalData.Update.formValidate.id = params.row.id;
                                                }
                                            }
                                        }, '修改'),
                                        h('Poptip', {
                                            props: {
                                                confirm: true,
                                                title: '您确定要删除这条数据吗?',
                                                transfer: true
                                            },
                                            on: {
                                                'on-ok': () => {
                                                    let id = params.row.id;
                                                    util.ajax.post('api/demand/delete/' + id).then(res => {
                                                        if (res.data.code === 200) {
                                                            this.modalAdd = false;
                                                            this.$Notice.success({
                                                                title: '删除成功',
                                                                duration: 2
                                                            });
                                                            this.initData();
                                                        } else {
                                                            // 删除失败
                                                            console.log('删除失败 -->', res.data);
                                                            this.$Notice.error({
                                                                title: res.data.msg,
                                                                duration: 5
                                                            });
                                                        }
                                                    });
                                                }
                                            }
                                        }, [
                                            h(
                                                'Button',
                                                {
                                                    props: {
                                                        type: 'error',
                                                        size: 'small',
                                                        icon: 'trash-b'
                                                    },
                                                    style: {
                                                        margin: '0 5px'
                                                    }
                                                },
                                                '删除'
                                            )]
                                        )
                                    ];
                                }
                            }
                        }
                    ],
                    data: [],
                    count: 0,
                    length: 10,
                    current_page: 1,
                    order: '-create_date'
                },
                modalData: {
                    Add: {
                        formValidate: {
                            project_id: '',
                            action_id: '',
                            name: '',
                            detail: '',
                            // complete_date: '',
                            imgList: [],
                            urgency_level: '1'
                        },
                        ruleValidate: {
                            project_id: [
                                { required: true, type: 'number', message: '请选择项目名称', trigger: 'blur' }
                            ],
                            action_id: [
                                { required: true, type: 'number', message: '请选择功能名称', trigger: 'blur' }
                            ],
                            name: [
                                { required: true, message: '需求名称不能为空', trigger: 'blur' }
                            ],
                            detail: [
                                { required: true, message: '需求描述不能为空', trigger: 'blur' }
                            ],
                            // complete_date: [
                            //     { required: true, type: 'date', message: '预计完成时间不能为空', trigger: 'blur' }
                            // ],
                            urgency_level: [
                                { required: true, type: 'number', message: '请选择需求紧急程度', trigger: 'blur' }
                            ]
                        },
                        formItemError: {
                            action_id: '',
                            project_id: '',
                            name: '',
                            detail: '',
                            urgency_level: ''
                        },
                        loading: false
                    },
                    Update: {
                        formValidate: {
                            name: '',
                            project_id: '',
                            id: ''
                        },
                        ruleValidate: {
                            name: [
                                { required: true, message: '用户名不能为空', trigger: 'blur' }
                            ],
                            project_id: [
                                { required: true, type: 'number', message: '请选择项目名称', trigger: 'blur' }
                            ]
                        },
                        formItemError: {
                            name: '',
                            project_id: ''
                        },
                        loading: false
                    }
                },
                actionData: [], // 所有功能信息
                projectData: [], // 所有项目信息
                searchData: {
                    status: '',
                    urgency_level: '',
                    project_id: '', // 项目id
                    developer_id: '', // 开发人员id
                    demandUser: 0 // 提需求人id
                },
                status_choices: [], // 状态筛选框数据
                urgency_level_choices: [], // 紧急程度筛选框数据
                demandUserData: [], // 提需求人选择框数据
                developerList: [] // 开发人员选择框数据
            };
        },
        methods: {
            // 初始化获取表格数据
            initData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': this.table_data.length,
                    'order': this.table_data.order,
                    'company_id': localStorage.company_id,
                    'id': this.table_data.data.id,
                    'status': this.searchData.status,
                    'urgency_level': this.searchData.urgency_level,
                    'project_id': this.searchData.project_id,
                    'developer_id': this.searchData.developer_id,
                    'demandUser': this.searchData.demandUser === 0 ? '' : this.searchData.demandUser
                };
                util.ajax.get('api/demand', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        console.log('res.data.data.ret_data;', res.data.data.ret_data);
                        this.table_data.data = res.data.data.ret_data;
                        this.table_data.count = res.data.data.data_count;
                        if (this.status_choices.length === 0) {
                            for (let index in res.data.data.status_choices) {
                                this.status_choices.push({id: res.data.data.status_choices[index][0], name: res.data.data.status_choices[index][1]});
                            }
                        }
                        if (this.urgency_level_choices.length === 0) {
                            for (let index in res.data.data.urgency_level_choices) {
                                this.urgency_level_choices.push({id: res.data.data.urgency_level_choices[index][0], name: res.data.data.urgency_level_choices[index][1]});
                            }
                        }

                        let demandUserData = [
                            {
                                id: 0,
                                name: '显示全部'
                            }
                        ];
                        for (let index in res.data.data.demand_user) {
                            demandUserData.push({id: res.data.data.demand_user[index].user_id, name: res.data.data.demand_user[index].user_name});
                        }
                        this.demandUserData = demandUserData;

                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 点击添加按钮
            modalAddDisplay () {
                // this.modalAdd = true;
                // this.$refs['AddformValidate'].resetFields();
                // console.log('this.roleData -->', this.roleData);
                this.currentPage = false;
                this.addDataPage = true;
            },
            // 点击修改按钮
            modalUpdateDisplay () {
                // console.log('this.UpdateData -->', this.UpdateData);
                // let imgList = this.UpdateData.img_list.split('|');
                // console.log('imgList -->', imgList);

                // imgList.each(function (item) {
                //     console.log('item -->', item);
                // });
                // let x = imgList.filter(function (item) {
                //     console.log('item -->', item);
                //     let returnData = {
                //         status: 'finished',
                //         url: item
                //     };
                //     return returnData;
                // });
                // let newImgList = [];
                // imgList.forEach(function (item) {
                //     if (item) {
                //         newImgList.push({
                //             status: 'finished',
                //             url: item
                //         });
                //     }
                //
                // });
                // this.UpdateData.img_list = newImgList;
                // console.log('this.UpdateData -->', this.UpdateData);
                this.currentPage = false;
                this.updateDataPage = true;
            },
            // 点击详情按钮
            modalDetailDisplay () {
                let imgList = this.detailData.img_list.split('|');
                let newImgList = [];
                imgList.forEach(function (item) {
                    if (item) {
                        newImgList.push({
                            status: 'finished',
                            url: item
                        });
                    }
                });
                this.detailData.img_list = newImgList;
                this.currentPage = false;
                this.detailDataPage = true;
            },
            // 修改
            modalUpdateFunc () {
                this.modalData.Update.loading = true;

                console.log('Update.loading -->', this.modalData.Update.loading);

                // 初始化所有字段错误信息的值
                for (let key in this.modalData.Update.formItemError) {
                    this.modalData.Update.formItemError[key] = '';
                }

                let params = {
                    'name': this.modalData.Update.formValidate.name,
                    'project_id': this.modalData.Update.formValidate.project_id
                };

                console.log('params -->', params);

                this.$refs['UpdateformValidate'].validate((valid) => {
                    if (valid) {
                        let params = {
                            'name': this.modalData.Update.formValidate.name,
                            'project_id': this.modalData.Update.formValidate.project_id
                        };

                        util.ajax.post('api/action/update/' + this.modalData.Update.formValidate.id, qs.stringify(params)).then(res => {
                            if (res.data.code === 200) {
                                console.log('修改成功 -->', res.data);
                                this.modalUpdate = false;
                                this.$Notice.success({
                                    title: '修改成功',
                                    duration: 2
                                });
                                this.initData();
                            } else {
                                // 修改失败
                                for (let key in res.data.msg) {
                                    this.modalData.Update.formItemError[key] = res.data.msg[key][0].message;
                                }
                            }

                            this.modalData.Update.loading = false;
                        });
                    } else {
                        // this.$Message.error('表单验证失败!');
                        this.modalData.Update.loading = false;
                    }
                });
            },

            // 当页码被改变是触发
            updateTableCurrentPage (currentPage) {
                this.table_data.current_page = currentPage;
                this.initData();
            },

            // 修改每页显示数量
            updateTablePageLength (length) {
                this.table_data.length = length;
                this.initData();
            },

            // 表格排序触发
            tableSort (e) {
                let key = e.key;
                let order = e.order;

                if (order === 'desc') {
                    this.table_data.order = '-' + key;
                } else {
                    this.table_data.order = key;
                }
                this.initData();
            },

            // 获取所有项目信息
            getProjectData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': 0,
                    'order': 'create_date',
                    'company_id': localStorage.company_id
                };

                util.ajax.get('api/project', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        this.projectData = res.data.data.ret_data;
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },
            // 获取开发人员信息
            userData () {
                let _this = this;
                let params = {
                    'length': 0,
                    'get_role_id': 4
                };
                util.ajax.get('api/user', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        console.log('res.data.data.ret_data', res.data.data.ret_data);
                        for (let index in res.data.data.ret_data) {
                            _this.developerList.push({name: res.data.data.ret_data[index].username, id: res.data.data.ret_data[index].id});
                        }
                        // console.log('_this.modalData.Audit.developerList -->', _this.modalData.Audit.developerList);
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 获取所有功能信息
            getActionData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': 0,
                    'order': 'create_date',
                    'company_id': localStorage.company_id
                };

                util.ajax.get('api/action', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        this.actionData = res.data.data.ret_data;
                        console.log('this.actionData --> ', this.actionData);
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 添加页面中的返回按钮被点击时触发
            closeAddPage () {
                console.log('点击添加的返回按钮');
                this.addDataPage = false;
                this.currentPage = true;
                this.initData();
            },
            // 修改页面中的返回按钮被点击时触发
            closeUpdatePage () {
                console.log('点击修改的返回按钮');
                this.updateDataPage = false;
                this.currentPage = true;
                this.initData();
            },
            // 详情页面中的返回按钮被点击时触发
            closeDetailPage () {
                console.log('点击详情的返回按钮');
                this.detailDataPage = false;
                this.currentPage = true;
                this.initData();
            }
        },
        created () {
            // if (localStorage.role_id === '3') {
            //     this.searchData.demandUser = localStorage.user_id;
            // }
            let demandsData = localStorage.demandsData ? JSON.parse(localStorage.demandsData) : {};
            demandsData.searchData ? this.searchData = demandsData.searchData : null;
            this.initData();
            this.getProjectData();
            this.getActionData();
            this.userData();
        },

        watch: {
            searchData: {
                handler: function (val, oldVal) {
                    let demandsData = localStorage.demandsData ? JSON.parse(localStorage.demandsData) : {};
                    demandsData.searchData = this.searchData;
                    localStorage.demandsData = JSON.stringify(demandsData);
                    this.table_data.current_page = 1;
                    this.initData();
                },
                deep: true
            }
        }
    };
</script>
